import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import router from 'next/router';
import { withTranslation } from 'next-i18next';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import Eventproxy from 'eventproxy';
import { Context } from './context';
import { initEvent } from './event';
import { motion } from 'framer-motion';
import * as Switch from '@radix-ui/react-switch';
import { Search, ChevronDown } from 'lucide-react';
import classNames from 'classnames';
import ModelConfig from './ModelConfig';

import { firmList, modelList, modelEnable } from '@/api/ai';

@withTranslation('common')
@withRouter
@connect(({ }) => ({}))
class Comp extends Component {
  controller = {};
  state = {
    // 事件对象
    event: new Eventproxy(),
    searchQuery: '',
    openDropdownId: null,
    showModelConfig: false,
    selectedModel: null,

    llmList: [],
    models: [],
  };

  componentDidMount() {
    this.init();
  }

  // 初始化
  init = async () => {
    const { event } = this.state;
    initEvent(event, this);
    this.getList();
  };

  getList = async () => {
    var reqData = {};
    var rs = await firmList(reqData);
    if (rs.data?.code == 200) {
      var data = rs.data.data;
      this.setState({ llmList: data });
    }
  };

  getModelList = async (item, index) => {
    const { openDropdownId, models } = this.state;
    var newId = openDropdownId == item.id ? null : item.id;
    this.setState({ openDropdownId: newId });
    if (!newId) {
      this.setState({ models: [] });
      return;
    }
    if (this.loading) return;
    var func = async () => {
      var reqData = {
        firm: item.name,
      };
      this.loading = true;
      var rs = await modelList(reqData);
      this.loading = false;
      if (rs.data?.code == 200) {
        var data = rs.data.data;
        this.setState({ models: data });
      }
    };

    if (openDropdownId) {
      this.setState({ models: [] }, () => {
        func();
      });
      return;
    }

    func();
  };

  getImg = (key) => {
    var base = '';
    if (router.basePath) {
      base = router.basePath;
    }
    var map = {
      azure: `${base}/img/models/azure.png`,
      openai: `${base}/img/models/openai.png`,
      tongyi: `${base}/img/models/tongyi.png`,
      deepseek: `${base}/img/models/deepseek.png`,
      anthropic: `${base}/img/models/anthropic.png`,
      default: `${base}/img/models/default.png`,
    };
    return map[key] ||map['default'];
  };

  handleSearchChange = (e) => {
    this.setState({ searchQuery: e.target.value });
  };

  toggleModelEnabled = async (item, checked, i) => {
    console.log(item);
    var reqData = {
      firm: item.firm,
      model: item.model,
      enabled: checked,
    };

    this.loading = true;
    var rs = await modelEnable(reqData);
    this.loading = false;
    if (rs.data?.code == 200) {
      this.state.models[i].is_enabled = checked;
      this.forceUpdate();
    }
  };

  openModelConfigDialog = (providerId, model) => {
    this.setState({
      showModelConfig: true,
      selectedModel: {
        ...model,
        providerId,
      },
    });
  };

  closeModelConfigDialog = () => {
    this.setState({
      showModelConfig: false,
      selectedModel: null,
    });
  };

  // 设置组件控制器
  setController = (name, compThis) => {
    this.controller[name] = compThis;
  };

  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  renderProviderCard = (provider, index) => {
    const { t } = this.props;
    const { openDropdownId, models } = this.state;
    const isDropdownOpen = openDropdownId === provider.id;

    // Create a ref for the dropdown button
    this.modelButtonRef = React.createRef();

    // Calculate dropdown position when it's open
    const calculateDropdownPosition = () => {
      if (this.modelButtonRef && this.modelButtonRef.current) {
        const rect = this.modelButtonRef.current.getBoundingClientRect();
        return {
          top: `${rect.bottom + 4}px`,
          left: `${rect.left}px`,
        };
      }
      return {};
    };

    return (
      <div key={provider.id}
        className={classNames(styles.providerCard, {
          [styles.providerCardDrpOpen]: isDropdownOpen,
        })}>
        <div className={styles.providerHeader}>
          <div className={styles.providerInfo}>
            <span className={styles.providerIcon}>
              <img src={this.getImg(provider.name)} alt={provider.name} />
            </span>
            <span className={styles.providerName}>{provider.name}</span>
          </div>

          <button
            className={styles.apiKeyButton}
            onClick={(e) => {
              e.stopPropagation();
              console.log(provider);
              this.openModelConfigDialog(provider.id, provider);
            }}
            title="Configure API Key"
          >
            <i
              className="iconfont icon-Feedback"
              style={{ fontSize: '16px' }}
            ></i>
            API-KEY
          </button>
        </div>

        <div className={styles.cardFooter}>
          <div
            ref={this.modelButtonRef}
            className={classNames(styles.modelCountBottom, {
              [styles.modelCountBottomColor]: isDropdownOpen,
            })}
            onClick={(e) => {
              if (provider.model_list.length == 0) {
                return;
              }
              e.stopPropagation();
              this.getModelList(provider, index);
            }}
            role="button"
            tabIndex={0}
          >
            <span>{provider.model_list.length} {t('Models')}{' '}</span>
            <span
              className={classNames(styles.chevron, {
                [styles.chevronOpen]: isDropdownOpen,
              })}
            >
              <ChevronDown size={16} />
            </span>
          </div>

          {isDropdownOpen && (
            <div
              className={styles.modelList}
              style={calculateDropdownPosition()}
            >
              {models.map((model, i) => (
                <div key={model.id} className={styles.modelItem}>
                  <div className={styles.modelName}>{model.model}</div>
                  <div className={styles.modelControls} onClick={(e) => e.stopPropagation()}>
                    <Switch.Root
                      className={styles.switchRoot}
                      checked={model.is_enabled}
                      onCheckedChange={(checked) => {
                        this.toggleModelEnabled(model, checked, i)
                      }}
                    >
                      <Switch.Thumb className={styles.switchThumb} />
                    </Switch.Root>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  };

  render() {
    // Context 全局参数 （所有后代都可获取调用）
    const { searchQuery, llmList } = this.state;

    var store = {
      ...this.state,
      controller: this.controller,
      setController: this.setController,
    };

    const filteredProviders = llmList.filter((provider) =>
      provider.name.toLowerCase().includes(searchQuery.toLowerCase()),
    );

    return (
      <Context.Provider value={store}>
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 0.5 }}
          style={{ height: '100%' }}
        >
          {/* Model Config Dialog */}
          {this.state.showModelConfig && (
            <ModelConfig
              model={this.state.selectedModel}
              onClose={this.closeModelConfigDialog}
            />
          )}
          <div className={styles.pageCont} onClick={() => {
            this.setState({ openDropdownId: null });
          }}>
            <div className={styles.header}>
              <h1 className={styles.title}>Model Providers</h1>
              <p className={styles.subtitle}>
                Configure your LLM providers and manage API settings.
              </p>
            </div>

            <div className={styles.searchContainer}>
              <div className={styles.searchInputWrapper}>
                <Search size={16} className={styles.searchIcon} />
                <input
                  type="text"
                  className={styles.searchInput}
                  placeholder="Search models"
                  value={searchQuery}
                  onChange={this.handleSearchChange}
                />
              </div>
            </div>

            <div className={styles.providersGrid}>
              {filteredProviders.map((provider, index) =>
                this.renderProviderCard(provider, index),
              )}
            </div>
          </div>
        </motion.div>
      </Context.Provider>
    );
  }
}

export default Comp;
